package org.giovanolli.mumi.dao.impl;

import java.util.Calendar;
import java.util.GregorianCalendar;

import org.apache.commons.lang.time.DateUtils;
import org.giovanolli.mumi.dao.AttentionTimeDao;
import org.giovanolli.mumi.entities.AttentionTime;
import org.giovanolli.mumi.entities.filter.AttentionTimeFilter;
import org.giovanolli.mumi.entities.filter.EntityFilter;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

/**
 * The Class AttentionTimeDaoImpl.
 */
@Repository("attentionTimeDao")
public class AttentionTimeDaoImpl extends HibernateDao<AttentionTime> implements AttentionTimeDao {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.giovanolli.mumi.dao.impl.HibernateDao#fillCriteria(org.giovanolli.mumi.entities.filter.EntityFilter, org.hibernate.criterion.DetachedCriteria)
	 */
	@Override
	protected DetachedCriteria fillCriteria(EntityFilter<AttentionTime> filter, DetachedCriteria criteria) {
		final AttentionTimeFilter entityFilter = (AttentionTimeFilter) filter;

		if (filter != null) {
			if (entityFilter.getPatient() != null) {
				criteria.add(Restrictions.eq("patient", entityFilter.getPatient()));
			}
			if (entityFilter.getSpecialist() != null) {
				criteria.createAlias("specialistFee", "specialistFee").add(Restrictions.eq("specialistFee.specialist", entityFilter.getSpecialist()));
			}
			if (entityFilter.getStartFilterDate() != null) {
				criteria.add(Restrictions.ge("date", entityFilter.getStartFilterDate()));
			}
			if (entityFilter.getEndFilterDate() != null) {
				Calendar calendar = GregorianCalendar.getInstance();
				long limitTime = entityFilter.getEndFilterDate().getTime() + (DateUtils.MILLIS_PER_DAY - 1);
				calendar.setTimeInMillis(limitTime);

				criteria.add(Restrictions.le("date", calendar.getTime()));
			}
			if (entityFilter.getAttentionTimeStatus() != null) {
				criteria.add(Restrictions.like("attentionTimeStatus", entityFilter.getAttentionTimeStatus()));
			}
		}
		return criteria;
	}
}
